package com.syf.config.resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

//遇到预检请求，要把过滤器写在了网关模块
@Configuration
public class HttpCorsFilterConfig {

    @Bean
    public CorsFilter corsFilter() {
        //跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //注意：要用addAllowedOriginPattern("*")，而不是allowedOrigins("*")
        corsConfiguration.addAllowedOrigin("*");  //允许http://www.xxx.com域发起跨域请求
        corsConfiguration.addAllowedHeader("*");  //允许跨域请求包含content-type
        corsConfiguration.addAllowedMethod("*");  //设置允许跨域请求的方法(get、post、put。。。)
        /*corsConfiguration.addAllowedMethod("OPTIONS");
        corsConfiguration.addAllowedMethod("HEAD");
        corsConfiguration.addAllowedMethod("GET");
        corsConfiguration.addAllowedMethod("PUT");
        corsConfiguration.addAllowedMethod("POST");
        corsConfiguration.addAllowedMethod("DELETE");
        corsConfiguration.addAllowedMethod("PATCH");*/

        corsConfiguration.setAllowCredentials(true);  // 允许cookie跨域
        corsConfiguration.setMaxAge(86400L);  //设置在86400秒不需要再发送预校验请求

        //跨域配置信息映射的容器：org.springframework.web.cors.UrlBasedCorsConfigurationSource
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);   //过滤器过滤地址

        return new CorsFilter(source);
    }

}
